package com.ykzb.pay.unionpay.action;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.ykzb.pay.unionpay.acp.sdk.LogUtil;
import com.ykzb.pay.unionpay.acp.sdk.SDKConstants;
import com.ykzb.pay.unionpay.acp.sdk.SDKUtil;

/**
 * 油卡充值前端页面
 * @author wyh
 *
 */
public class GasReturnAction {
	public ModelAndView defaultMethod(HttpServletRequest req,
			HttpServletResponse response) throws UnsupportedEncodingException {
		LogUtil.writeLog("FrontRcvResponse前台接收报文返回开始");
		req.setCharacterEncoding("ISO-8859-1");
		String encoding = req.getParameter(SDKConstants.param_encoding);
		LogUtil.writeLog("返回报文中encoding=[" + encoding + "]");
		Map<String, String> respParam = getAllRequestParam(req);

		// 打印请求报文
		LogUtil.printRequestLog(respParam);

		Map<String, String> valideData = null;
		StringBuffer page = new StringBuffer();
		page.append("<table>");
		if (null != respParam && !respParam.isEmpty()) {
			Iterator<Entry<String, String>> it = respParam.entrySet()
					.iterator();
			valideData = new HashMap<String, String>(respParam.size());
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				String key = e.getKey();
				String value = e.getValue();
				value = new String(value.getBytes("ISO-8859-1"), encoding);
				page.append("<tr><td width=\"30%\" align=\"right\">" + key
						+ "(" + key + ")</td><td>" + value + "</td></tr>");
				valideData.put(key, value);
			}
		}
		if (!SDKUtil.validate(valideData, encoding)) {
			page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>失败</td></tr>");
			LogUtil.writeLog("验证签名结果[失败].");
			page.append("</table>");
			
			req.setAttribute("error", "支付失败");
			LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束");
			return new ModelAndView("/website/error");
		} else {
			page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>成功</td></tr>");
			LogUtil.writeLog("验证签名结果[成功].");
			page.append("</table>");
			LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束");

			String orderId = valideData.get("orderId"); //其他字段也可用类似方式获取
			//GasManager.payOrderSuccess(orderId, 4);
			req.setAttribute("error", "支付成功");
			return new ModelAndView("/website/error");
		}

	}
	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(
			final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				if (res.get(en) == null || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
}
